import React, { useState, useEffect, useRef } from 'react'
import { Button, Table, Modal, Switch } from 'antd'
import { DeleteOutlined, EditOutlined, ExclamationCircleOutlined } from '@ant-design/icons'
import axios from '../../../util/http'
import UserForm from '../../../components/user-manage/UserForm';
const { confirm } = Modal;

export default function UserList() {

  const [dataSource, setDataSource] = useState([])
  const [isVisible, setIsVisible] = useState(false)
  const [regionList, setRegionList] = useState([])
  const [roleList, setRoleList] = useState([])
  const [isUpdateVisible, setIsUpdateVisible] = useState(false)
  const [isUpdateDisable, setIsUpdateDisable] = useState(false)
  const [current, setCurrent] = useState(null)

  const addForm = useRef(null)
  const updateForm = useRef(null)

  const confirmMessage = (item) => {
    confirm({
      title: 'Do you Want to delete these items?',
      icon: <ExclamationCircleOutlined />,
      content: 'Some descriptions',
      onOk() {
        // console.log('OK');
        deleteMethod(item)
      },
      onCancel() {
        console.log('Cancel');
      },
    });
  }

  // 删除函数
  const deleteMethod = (item) => {
    // console.log(item);
    // 后端 + 页面全部要删除

    setDataSource(dataSource.filter(data => data.id !== item.id))
    axios.delete(`/users/${item.id}`).then(res => {
      console.log('删除成功');
      console.log(res);
    })
  }

  const handleChange = (item) => {
    item.roleState = !item.roleState
    setDataSource([...dataSource])
    axios.patch(`/users/${item.id}`, {
      roleState: item.roleState
    })
  }

  const handleUpdate = (item) => {
    setTimeout(() => {
      setIsUpdateVisible(true)
      if (item.roleId === 1) {
        // 禁用
        setIsUpdateDisable(true)
      } else {
        // 取消禁用
        setIsUpdateDisable(false)
      }
      updateForm.current.setFieldsValue(item)
    })

    setCurrent(item)
  }

  const columns = [
    {
      title: '区域',
      dataIndex: 'region',
      filters: [
        ...regionList.map(item => ({
          text: item.title,
          value: item.value
        })),
        {
          text: "全球",
          value: "全球"
        }
      ],
      onFilter: (value, record) => {
        if (value === '全球') {
          return record.region === ""
        }
        return record.region === value
      },
      render: (region) => {
        return <span>{region !== '' ? region : '全球'}</span>
      }
    },
    {
      title: '角色名称',
      dataIndex: 'role',
      render: (item) => {
        return item?.roleName
      }
    },
    {
      title: '用户名',
      dataIndex: 'username',
    },
    {
      title: '用户状态',
      dataIndex: 'roleState',
      render: (roleState, item) => {
        return <Switch onChange={() => handleChange(item)} checked={roleState} disabled={item.default}></Switch>
      }
    },
    {
      title: '操作',
      render: (item) => {
        return <div>
          <Button danger shape="circle" icon={<DeleteOutlined />} onClick={() => confirmMessage(item)} disabled={item.default}></Button>
          <Button
            type='primary'
            shape="circle"
            disabled={item.default}
            icon={<EditOutlined />}
            onClick={() => handleUpdate(item)}
          ></Button>
        </div>
      }
    }
  ];

  const { roleId, region, username } = JSON.parse(localStorage.getItem("token"))

  useEffect(() => {
    const roleObj = {
      "1": "superadmin",
      "2": "admin",
      "3": "editor"
    }
    axios.get("/users?_expand=role").then(res => {
      const list = res.data
      setDataSource(roleObj[roleId] === "superadmin" ? list : [
        ...list.filter(item => item.username === username),
        ...list.filter(item => item.region === region && roleObj[item.roleId] === "editor")
      ])
    })
  }, [roleId, region, username])

  useEffect(() => {
    axios.get("/regions").then(res => {
      setRegionList(res.data)
    })
  }, [])

  useEffect(() => {
    axios.get("/roles").then(res => {
      setRoleList(res.data)
    })
  }, [])

  const addFormOK = () => {
    // 触发表单验证
    addForm.current.validateFields().then(value => {
      // 添加数据
      // console.log("添加的数据", value);
      setIsVisible(false)
      addForm.current.resetFields()
      axios.post(`/users`, {
        ...value,
        "roleState": true,
        "default": false
      }).then(res => {
        // console.log(res.data);
        setDataSource([...dataSource, {
          ...res.data,
          role: roleList.filter(item => item.id === value.roleId)[0]
        }])
      })
    }).catch(err => {
      console.log(err);
    })

  }

  const updateFormOK = () => {
    updateForm.current.validateFields().then(value => {
      // 添加数据
      console.log("添加的数据", value);
      setIsUpdateVisible(false)
      setDataSource(dataSource.map(item => {
        if (item.id === current.id) {
          return {
            ...item,
            ...value,
            role: roleList.filter(data => data.id === value.roleId)[0]
          }
        }
        return item
      }))
      setIsUpdateDisable(!isUpdateDisable)
      axios.patch(`/users/${current.id}`, value)
    })
  }

  return (
    <div style={{ height: '100vh' }}>
      <Button type='primary' onClick={() => { setIsVisible(true) }}>添加用户</Button>
      <Table
        dataSource={dataSource}
        columns={columns}
        pagination={{
          pageSize: 5
        }}
        rowKey={item => item.id}
      />

      <Modal
        visible={isVisible}
        title="添加用户"
        okText="确定"
        cancelText="取消"
        onCancel={() => setIsVisible(false)}
        onOk={() => addFormOK()}
      >
        <UserForm
          ref={addForm}
          regionList={regionList}
          roleList={roleList}>
        </UserForm>

      </Modal>

      <Modal
        visible={isUpdateVisible}
        title="更新用户"
        okText="更新"
        cancelText="取消"
        onCancel={() => {
          setIsUpdateVisible(false)
          setIsUpdateDisable(!isUpdateDisable)

        }}
        onOk={() => updateFormOK()}
      >
        <UserForm
          ref={updateForm}
          regionList={regionList}
          roleList={roleList}
          isUpdateDisable={isUpdateDisable}
          isUpdate={true}
        ></UserForm>

      </Modal>
    </div>
  )
}

